<?php
/*
 * 系统异常类
 */
class Kohana_Exception extends Kohana_Kohana_Exception 
{
	public static function handler (Exception $e)
	{
		// 权限拒绝(ACL)的异常处理
		if ($e instanceof Exception_Access)
		{
			if (Request::initial()->controller() == 'passport')
				Request::initial()->redirect('/admin');

			if (site::type() == 'merchant' || site::type() == 'member' || site::type() == 'manager')
			{
				if (! user::is_login())
					Request::initial()->redirect('/passport/login');
			}
		}

		if ($e instanceof HTTP_Exception_404)
		{
		}


		// 如果是开发阶段, 则由系统默认处理
		if (Kohana::DEVELOPMENT === Kohana::$environment)
		{
			parent::handler($e);
		}
		else
		// 生产阶段，则进入自定义错误处理
		{

			try 
			{
				$txt_error = parent::text($e);

				// 记录错误日志
				if (is_object(Kohana::$log))
				{
					// Add this exception to the log
					Kohana::$log->add(Log::ERROR, $txt_error);

					// Make sure the logs are written
					Kohana::$log->write();
				}

				if (Kohana::$is_cli)
				{
					// Just display the text of the exception
					echo "$txt_error";
					exit(1);
				}


				if (Request::$current !== NULL AND Request::current()->is_ajax() === TRUE)
				{
					// Just display the text of the exception
					echo "\n{$txt_error}\n";
					exit(1);
				}


				$param = array(
					'action'  => $e instanceof HTTP_Exception ? 
											$e->getCode() : 500,
					'message' => rawurlencode($e->getMessage()),
				);

				$req = Request::factory(Route::get('error')->uri($param));
				$req->execute()->send_headers();
				echo $req->render();
                Kohana_Exception::$error_view = 'www/not_found';
			}
			catch (Exception $e)
			{
				ob_get_level() AND ob_clean();
                Kohana_Exception::$error_view = 'www/not_found';
                parent::handler($e);
//				echo parent::text($e);
//				exit(1);
			}
		}
	}
}
